#
# @lc app=leetcode.cn id=450 lang=python
#
# [450] 删除二叉搜索树中的节点
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def deleteNode(self, root, key):
        """
        :type root: Optional[TreeNode]
        :type key: int
        :rtype: Optional[TreeNode]
        """
        self.key = key
        if not root:
            return 
        root = self.loop(root)
        return root
    def loop(self, node):
        if node is None:
            return 
    
        if node.val < self.key:
            node.right = self.loop(node.right)

        elif node.val > self.key:
            node.left = self.loop(node.left)
        
        else:
            if node.left is None:
                node = node.right
            elif node.right is None:
                node = node.left
            elif node.left is None and node.right is None:
                node = None
            else:
                cur = node.right
                while cur.left:
                    cur = cur.left
                cur.left = node.left
                return node.right
            
        return node
        
# @lc code=end

